# 1.7 练习题：学籍注册程序
# 需求：
# 1. 要求⽤户输⼊姓名、年龄、⼿机号、身份证号、所选课程，然后为学员完成注册
# 2. ⼿机号、身份证号唯⼀
# 3. 可选的课程只能从Python、Linux、⽹络安全、前端、数据分析 这⼏⻔⾥选
# 4. 学员信息存⼊⽂件

import json, os


def zhuce(data):
    # ids = []
    # for s in data:  # 提取已存在的身份证号
    #     ids.append(data[s][2])
    ids = [data[s][2] for s in data]  # 提取已存在的身份证号
    while True: # 姓名合法性检查
        name = input('请输入姓名：')
        if name:
            break
        print('姓名不能为空！请重新输入...')
    while True: # 年龄合法性检查
        age = input('请输入年龄：')
        try:
            temp = int(age)
            if temp<0:
                print('年龄输入不合法！请重新输入...')
            elif temp>200:
                print('年龄输入过大！请重新输入...')
            break
        except:
            print('年龄输入不合法！请重新输入...')
    while True: # 手机号合法性、唯一性检查
        tel = input('请输入手机号：')
        try:
            temp = int(tel)
            if temp>10000000000 and temp<20000000000:
                if tel not in data:
                    data[tel] = []
                    data[tel].append(name)
                    data[tel].append(age)
                    break
                print('手机号已存在！请重新输入...')
            print('手机号输入不合法！请重新输入...')
        except Exception as e:
            # print(e)
            print('手机号输入不不不合法！请重新输入...')
    while True: # 身份证号合法性、唯一性检查（只检查长度）
        id = input('请输入身份证号：')
        if id not in ids:
            if len(id)==18:
                data[tel].append(id)
                break
            print('身份证号长度不合法！请重新输入...')
        print('身份证号已存在！请重新输入...')
    courses = ('Python','Linux','⽹络安全','前端','数据分析')
    while True:
        print('可选课程：')
        for i in range(len(courses)):
            print('{}、{}'.format(i+1, courses[i]))
        # 课程选择合法性检查
        try:
            k = int(input('请选择课程（序号）：'))
            if k>=1 and k<=len(courses):
                data[tel].append(courses[k-1])
                break
            print('超出范围！请重新选择...')
        except:
            print('键入错误！请重新选择...')
    return data

if __name__ == '__main__':
    # 存储格式：{"tel":["name","age","id","course"]}
    # with open('data.json', 'w', encoding='utf-8') as fp:
    #     fp.write('{}')
    with open('data.json', 'r', encoding='utf-8') as fp:
        # text = fp.read()
        # print(text)
        # data = json.loads(text)
        # print(data)
        # newdata = zhuce(data)
        # print(newdata)
        # jsonStr = json.dumps(newdata)
        # print(jsonStr)
        # with open('newdata.json', 'w', encoding='utf-8') as newfp:
        #     newfp.write(str(jsonStr))
        data = json.load(fp)
        # print(data)
        newdata = zhuce(data)
        # print(newdata)
        with open('newdata.json', 'w', encoding='utf-8') as newfp:
            json.dump(newdata, newfp, ensure_ascii=False)
    os.remove('data.json')
    os.rename('newdata.json', 'data.json')


